package com.opengate.base.threadpool;

import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 自定义线程池
 *     <p>使用注入 @Autowired private Executor threadPoolExecutor;
 * @date 2023/3/14 6:32 PM
 */
@EnableAsync
@AllArgsConstructor
public class BaseThreadPoolExecutor {

    private Integer corePoolSize;

    private Integer maxPoolSize;

    public Executor threadPoolExecutor() {

        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();

        // 核心线程数
        threadPoolExecutor.setCorePoolSize(corePoolSize);
        // 最大线程数
        threadPoolExecutor.setMaxPoolSize(maxPoolSize);

        // 队列长度
        threadPoolExecutor.setQueueCapacity(maxPoolSize * 10);

        // 线程空闲时间
        threadPoolExecutor.setKeepAliveSeconds(300);

        // 线程名字前缀
        threadPoolExecutor.setThreadNamePrefix("open-gate-Executor-");

        /**
         * 拒绝处理策略 CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。 AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。 DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        threadPoolExecutor.setRejectedExecutionHandler(
                new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());

        // 线程初始化
        threadPoolExecutor.initialize();

        return threadPoolExecutor;
    }
}
